package com.zzmcc.sys.controller;


import com.jfinal.ext.kit.PoiKit;
import com.jfinal.ext.kit.PoiKit.Pair;
import com.jfinal.ext.render.excel.JxlsRender;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.zzmcc.base.BaseController;
import util.ChristStringUtil;
import util.Levenshtein;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class CompareController extends BaseController {
	public void index() {

		render("../compare.html");
	}
	public void down(){
		String path =PathKit.getWebRootPath() + "/tpl_compare.xls";
		String templateFileName = PathKit.getRootClassPath() + "/tpl_compare.xls";

		renderFile(new File(templateFileName));
	}
	public void export(){

		String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		UploadFile file = getFile();

		String fileName = null;

		if (file !=null) {
			File source = file.getFile();
			fileName = file.getFileName();

			try {
				FileInputStream fis = new FileInputStream(source);
				File targetDir = new File(PathKit.getWebRootPath()  + "/u/" + path);
				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}
				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[300];
				while (fis.read(bts, 0, 300) != -1) {
					fos.write(bts, 0, 300);
				}
				fos.close();
				fis.close();

				source.delete();


			} catch (FileNotFoundException e) {

				renderDWZErrorJson("上传出现错误，请稍后再上传");
			} catch (IOException e) {

				renderDWZErrorJson("文件写入服务器出现错误，请稍后再上传");
			}
		}
		String templateFileName = PathKit.getWebRootPath()  + "/u/" + path +"/" +fileName;
		List<Record> records  = new ArrayList<Record>();
		Object[][] dataArr1 = PoiKit.ReadExcel(templateFileName, "原始数据");
		Object[][] dataArr2 = PoiKit.ReadExcel(templateFileName,"匹配数据");
		for(int i=1;i<dataArr1.length;i++){
			Object[] rowArr1 = dataArr1[i];
			Record record = new Record();
			//匹配
			java.text.DecimalFormat   df=new   java.text.DecimalFormat("#.##");
			String name =rowArr1[1].toString();
			double iniSimilar =0;
			for(int m = 1;m < dataArr2.length;m++){
				Object[] rowArr2 = dataArr2[m];
				String key=rowArr2[0].toString();
				String value=rowArr2[1].toString();
				double similar = Levenshtein.getSimilarityRatio(name,key);
				if(similar>iniSimilar){
					iniSimilar=similar;
					record.set("similar",df.format(similar));
					record.set("key",key);
					record.set("value", value);
				}

			}
			record.set("id", rowArr1[0]);
			record.set("name",rowArr1[1]);


			records.add(record);
		}

		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("records", records);
		String filename = "compare.xls";
		render(JxlsRender.me(templateFileName).filename(filename).beans(beans));


	}


}
